package ru.spies.loginOrRegistration;

import javax.servlet.http.HttpServletRequest;

import ru.spies.dbwork.DBWork;
import ru.spies.entities.Siteuser;
import ru.spies.forms.LoginOrRegistrationForm;
import ru.spies.profileClasses.UserInfo;


public class LoginWork extends AbstractLoginOrRegistrationWork{
	
	private static LoginWork statThis;

	public LoginWork() {
		
	}
	
	public static LoginWork getInstance(){
		if (statThis==null){
			statThis = new LoginWork();
		}
		return statThis;
	}

	@Override
	protected String createForm(HttpServletRequest request) {
		String login = request.getParameter("loginField");
		if (login.isEmpty()) return LoginOrRegistrationForm.getInstance().createFailureForm(EMPTY_LOGIN);
		String password = request.getParameter("passwordField");
		if (login.isEmpty()) return LoginOrRegistrationForm.getInstance().createFailureForm(EMPTY_PASSWORD); 
		Siteuser user = new Siteuser();
		user.setParamForFindQuery(login);
		user=(Siteuser) DBWork.getInstance().findObjectFromTable(user);
		if (user==null) return LoginOrRegistrationForm.getInstance().createFailureForm(WRONG_LOGIN_OR_PASSWORD); 
		if (!PasswordGenerator.getInstance().isPasswordRight(password, user.getPassword())) return LoginOrRegistrationForm.getInstance().createFailureForm(WRONG_LOGIN_OR_PASSWORD);
		UserInfo.getInstance().login(user);
		return LoginOrRegistrationForm.getInstance().createSuccessfulForm();
	}

}
